package com.example.bootdemo.service.impl;

import com.example.bootdemo.pojo.Role;
import com.example.bootdemo.pojo.User;
import com.example.bootdemo.pojo.UserRole;
import com.example.bootdemo.repository.RoleRepository;
import com.example.bootdemo.repository.TblUserRepository;
import com.example.bootdemo.repository.UserRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private TblUserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userRepository.findUserByUsername(username);
        if(user==null){
            return null;
        }
        Long userId = user.getUserId();
        List<UserRole> userRoleList = userRoleRepository.findByUserId( userId);
        if(userRoleList.size()>0){
            List<String> roleIds = new ArrayList<>();
            for(UserRole userRole: userRoleList){
                roleIds.add(userRole.getRoleId());
            }
            List<Role> roles = roleRepository.findRolesByRoleIdIn(roleIds);
            user.setRoles(roles);
        }
        return user;
    }
}
